/*
 * VigenereEncryptor.cpp
 *
 *  Created on: 06/11/2011
 *      Author: Marcos Rimoldi
 */

#include "VigenereEncryptor.h"
#include "EncryptionProperties.h"


VigenereEncryptor::VigenereEncryptor() {

}

VigenereEncryptor::~VigenereEncryptor() {

}

string VigenereEncryptor::encipher(string plainText) {

	string keyword = EncryptionProperties::getVigenereKey();
	string encrypted = "";
	unsigned int j = 0;
	for (unsigned int i=0; i < plainText.length(); i++) {

		if (toascii(plainText[i]) > 32 && toascii(plainText[i]) < 127) {
			if (j >= keyword.length()) {
				j = 0;
			}
			encrypted.append(1,(char)((((toascii(plainText[i]) - 33) + (toascii(keyword[j]) - 33)) % 94) + 33));
			j++;
		}
		else {
			//cout << "Encriptando algo fuera de ascii: " << toascii(plainText[i]) << endl;
			stringstream ss;
			ss << plainText[i];
			encrypted.append(ss.str());
		}
	}
	return encrypted;
}


string VigenereEncryptor::decipher(string cipherText) {

	string keyword = EncryptionProperties::getVigenereKey();
	string deciphered = "";
	int j = 0;
	for (int i=0; i < cipherText.length(); i++) {

		if (toascii(cipherText[i]) > 32 && toascii(cipherText[i]) < 127) {
			if (j >= keyword.length()) {
				j = 0;
			}

			int index = ((toascii(cipherText[i])-33)-(toascii(keyword[j])-33));
			if (index < 0) {
				index += 94;
			}
			deciphered.append(1,(char)((index % 94)+33));
			j++;
		}
		else {
				//if (toascii(cipherText[i]) != 10 || toascii(cipherText[i]) != 13) {
					//cout << "Desencriptando algo fuera de ascii: " << toascii(cipherText[i]) << endl;
					stringstream ss;
					ss << cipherText[i];
					deciphered.append(ss.str());
				//}
		}
	}
	return deciphered;
}


